<template>
  <div class="manual-matting-editor" v-if="visible">
    <div class="editor-overlay" @click="handleClose">
      <div class="editor-container" @click.stop>
        <!-- 顶部工具栏 -->
        <div class="editor-header">
          <button class="back-btn" @click="handleClose" :disabled="isSaving">
            ← 返回
          </button>
          <div class="header-actions">
            <button class="action-btn undo-btn" @click="undo" :disabled="!canUndo || isSaving || isConfirmed">
              ↶ 撤销
            </button>
            <button class="action-btn confirm-btn" @click="confirmEdit" :disabled="isSaving">
              {{ isSaving ? '保存中...' : '✓ 确认' }}
            </button>
            <button class="action-btn download-btn" @click="downloadCurrent" :disabled="isSaving">
              ↓ 下载
            </button>
          </div>
        </div>

        <!-- 主编辑区 -->
        <div class="editor-main">
          <!-- 左侧：画布区域 -->
          <div class="canvas-section">
            <div class="canvas-container">
              <!-- 对比视图 -->
              <div class="canvas-wrapper">
                <!-- 原图 -->
                <div class="canvas-box">
                  <h4 class="canvas-title">原图</h4>
                  <div class="canvas-content checkered-bg">
                    <canvas ref="originalCanvas" class="canvas"></canvas>
                  </div>
                </div>

                <!-- 编辑结果 -->
                <div class="canvas-box">
                  <h4 class="canvas-title">编辑结果</h4>
                  <div class="canvas-content" :class="getBackgroundClass()" :style="getBackgroundStyle()">
                    <canvas 
                      ref="editCanvas" 
                      class="canvas edit-canvas"
                      :class="{ 'canvas-disabled': isConfirmed }"
                      @mousedown="startDrawing"
                      @mousemove="draw"
                      @mouseup="stopDrawing"
                      @mouseleave="stopDrawing"
                      @touchstart="handleTouchStart"
                      @touchmove="handleTouchMove"
                      @touchend="stopDrawing"
                    ></canvas>
                  </div>
                </div>
              </div>

            </div>
          </div>

          <!-- 右侧：工具面板 -->
          <div class="tools-panel">
            <h3 class="panel-title">擦除工具</h3>

            <!-- 工具选择 -->
            <div class="tool-group">
              <label class="tool-label">工具模式</label>
              <div class="tool-buttons">
                <button 
                  class="tool-btn" 
                  :class="{ active: currentTool === 'eraser' }"
                  @click="currentTool = 'eraser'"
                  :disabled="isSaving || isConfirmed"
                >
                  擦除
                </button>
                <button 
                  class="tool-btn" 
                  :class="{ active: currentTool === 'restore' }"
                  @click="currentTool = 'restore'"
                  :disabled="isSaving || isConfirmed"
                >
                  涂抹还原
                </button>
              </div>
            </div>

            <!-- 画笔大小 -->
            <div class="tool-group">
              <label class="tool-label">
                <span>画笔大小</span>
                <span class="tool-value">{{ brushSize }}px</span>
              </label>
              <input 
                type="range" 
                v-model.number="brushSize" 
                min="5" 
                max="200" 
                step="5"
                class="tool-slider"
                :disabled="isSaving || isConfirmed"
              />
              <div class="slider-marks">
                <span>5px</span>
                <span>100px</span>
                <span>200px</span>
              </div>
            </div>

            <!-- 硬度 -->
            <div class="tool-group">
              <label class="tool-label">
                <span>硬度</span>
                <span class="tool-value">{{ hardness }}%</span>
              </label>
              <input 
                type="range" 
                v-model.number="hardness" 
                min="0" 
                max="100" 
                step="10"
                class="tool-slider"
                :disabled="isSaving || isConfirmed"
              />
              <div class="slider-marks">
                <span>软</span>
                <span>中</span>
                <span>硬</span>
              </div>
            </div>

            <!-- 背景色选择 -->
            <!-- 背景颜色 -->
            <div class="tool-group">
              <label class="tool-label">
                <span>背景颜色</span>
                <button class="transparent-btn" @click="bgColor = 'transparent'" :class="{ active: bgColor === 'transparent' }" :disabled="isSaving">
                  透明
                </button>
              </label>
              <div class="color-picker-wrapper">
                <input 
                  type="color" 
                  v-model="bgColor" 
                  class="color-picker-input"
                  @input="handleColorChange"
                  :disabled="isSaving"
                />
                <input 
                  type="text" 
                  v-model="bgColor" 
                  class="color-text-input"
                  placeholder="#FFFFFF"
                  @input="handleColorChange"
                  :disabled="isSaving"
                />
              </div>
            </div>

            <!-- 提示信息 -->
            <div class="tool-hint">
              <p><strong>提示：</strong></p>
              <p>• 使用擦除工具移除不需要的部分</p>
              <p>• 使用涂抹还原工具恢复原图颜色</p>
              <p>• 调整画笔大小和硬度以获得更好的效果</p>
              <p>• 选择背景颜色预览抠图效果</p>
              <p>• 完成后点击"确认"保存结果，将替换原抠图记录</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义确认对话框 -->
    <ConfirmDialog
      v-model:visible="showConfirmDialog"
      :title="confirmDialogTitle"
      :message="confirmDialogMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="handleDialogConfirm"
      @cancel="handleDialogCancel"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { toastSuccess, toastError } from '@/utils/toast'
import ConfirmDialog from './ConfirmDialog.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  imageUrl: {
    type: String,
    required: true
  },
  originalImageUrl: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['close', 'confirm'])

// Canvas 引用
const originalCanvas = ref(null)
const editCanvas = ref(null)

// 画布状态
const originalCtx = ref(null)
const editCtx = ref(null)
const originalImage = ref(null)  // 用户上传的原始图片
const mattingImage = ref(null)   // AI抠图结果
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)
// 缓存绘制时的矩形与缩放，避免每次 mousemove 强制布局
const cachedRect = ref(null)
const cachedScaleX = ref(1)
const cachedScaleY = ref(1)
// 使用 rAF 合批绘制，降低高频 mousemove 带来的抖动与开销
let rafId = null
const pendingPoint = ref(null)

// 工具参数
const currentTool = ref('eraser') // 'eraser' or 'restore'
const brushSize = ref(30)
const hardness = ref(50)
// const zoom = ref(1)  // 暂时不使用缩放功能
const bgColor = ref('transparent')

// 历史记录（用于撤销）
const history = ref([])
const maxHistory = 20
const canUndo = ref(false)

// 保存状态（用于禁用控件）
const isSaving = ref(false)
const isConfirmed = ref(false) // 🔑 确认后禁止使用画笔

// 确认对话框状态
const showConfirmDialog = ref(false)
const confirmDialogTitle = ref('确认')
const confirmDialogMessage = ref('')
const confirmDialogCallback = ref(null)
const confirmDialogCancelCallback = ref(null)

// 初始化
const init = async () => {
  await nextTick()
  
  if (!originalCanvas.value || !editCanvas.value) {
    console.error('Canvas elements not found')
    return
  }

  // 加载原始图片（用户上传的）
  const originalImgUrl = props.originalImageUrl || props.imageUrl
  const originalImg = new Image()
  originalImg.crossOrigin = 'anonymous'
  
  originalImg.onload = () => {
    originalImage.value = originalImg
    
    const width = originalImg.width
    const height = originalImg.height
    
    // 设置原图 canvas - 显示用户上传的原始图片
    originalCanvas.value.width = width
    originalCanvas.value.height = height
    originalCtx.value = originalCanvas.value.getContext('2d')
    originalCtx.value.drawImage(originalImg, 0, 0, width, height)
    
    // 加载AI抠图结果
    const mattingImg = new Image()
    mattingImg.crossOrigin = 'anonymous'
    
    mattingImg.onload = () => {
      mattingImage.value = mattingImg
      
      // 设置编辑 canvas - 显示AI抠图结果
      editCanvas.value.width = width
      editCanvas.value.height = height
      editCtx.value = editCanvas.value.getContext('2d', { willReadFrequently: true })
      editCtx.value.drawImage(mattingImg, 0, 0, width, height)
      
      // 保存初始状态到历史
      saveHistory()
      
      console.log('Manual matting editor initialized:', width, 'x', height)
    }
    
    mattingImg.onerror = () => {
      toastError('抠图结果加载失败')
      handleClose()
    }
    
    mattingImg.src = props.imageUrl
  }
  
  originalImg.onerror = () => {
    toastError('原始图片加载失败')
    handleClose()
  }
  
  originalImg.src = originalImgUrl
}

// 保存当前状态到历史
const saveHistory = () => {
  if (!editCanvas.value) return
  
  const imageData = editCtx.value.getImageData(0, 0, editCanvas.value.width, editCanvas.value.height)
  history.value.push(imageData)
  
  // 限制历史记录数量
  if (history.value.length > maxHistory) {
    history.value.shift()
  }
  
  canUndo.value = history.value.length > 1
}

// 撤销
const undo = () => {
  if (history.value.length <= 1) return
  
  // 移除当前状态
  history.value.pop()
  
  // 恢复上一个状态
  const lastState = history.value[history.value.length - 1]
  editCtx.value.putImageData(lastState, 0, 0)
  
  canUndo.value = history.value.length > 1
  toastSuccess('已撤销')
}

// 开始绘制
const startDrawing = (e) => {
  // 🔑 确认后禁止绘制
  if (isConfirmed.value || isSaving.value) return
  
  isDrawing.value = true
  cachedRect.value = editCanvas.value.getBoundingClientRect()
  cachedScaleX.value = editCanvas.value.width / cachedRect.value.width
  cachedScaleY.value = editCanvas.value.height / cachedRect.value.height
  lastX.value = (e.clientX - cachedRect.value.left) * cachedScaleX.value
  lastY.value = (e.clientY - cachedRect.value.top) * cachedScaleY.value
}

// 绘制
const draw = (e) => {
  // 🔑 确认后禁止绘制
  if (isConfirmed.value || isSaving.value || !isDrawing.value) return
  const x = (e.clientX - cachedRect.value.left) * cachedScaleX.value
  const y = (e.clientY - cachedRect.value.top) * cachedScaleY.value
  // 记录目标点，使用 rAF 执行一次绘制，避免高频多次重绘
  pendingPoint.value = { x, y }
  if (rafId == null) {
    rafId = requestAnimationFrame(() => {
      const point = pendingPoint.value
      pendingPoint.value = null
      rafId = null
      if (!point) return
      const ctx = editCtx.value
      // 设置画笔
      ctx.lineWidth = brushSize.value
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      if (currentTool.value === 'eraser') {
        ctx.globalCompositeOperation = 'destination-out'
        const opacity = 0.3 + (hardness.value / 100) * 0.7
        ctx.globalAlpha = opacity
        // 线性擦除
        ctx.beginPath()
        ctx.moveTo(lastX.value, lastY.value)
        ctx.lineTo(point.x, point.y)
        ctx.stroke()
      } else {
        // 涂抹还原：使用原始图片内容绘制到圆形区域
        ctx.globalCompositeOperation = 'source-over'
        ctx.globalAlpha = 1.0
        if (originalImage.value) {
          ctx.save()
          ctx.beginPath()
          ctx.arc(point.x, point.y, brushSize.value / 2, 0, Math.PI * 2)
          ctx.clip()
          ctx.drawImage(
            originalImage.value,
            0, 0,
            editCanvas.value.width,
            editCanvas.value.height
          )
          ctx.restore()
        }
      }
      lastX.value = point.x
      lastY.value = point.y
    })
  }
}

// 停止绘制
const stopDrawing = () => {
  if (isDrawing.value) {
    isDrawing.value = false
    if (rafId != null) {
      cancelAnimationFrame(rafId)
      rafId = null
      pendingPoint.value = null
    }
    saveHistory()
    cachedRect.value = null
  }
}

// 触摸事件处理
const handleTouchStart = (e) => {
  // 🔑 确认后禁止绘制
  if (isConfirmed.value || isSaving.value) return
  
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousedown', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  editCanvas.value.dispatchEvent(mouseEvent)
}

const handleTouchMove = (e) => {
  // 🔑 确认后禁止绘制
  if (isConfirmed.value || isSaving.value) return
  
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousemove', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  editCanvas.value.dispatchEvent(mouseEvent)
}

// 删除了重置功能

// 缩放控制 - 暂时禁用
// const zoomIn = () => {
//   if (zoom.value < 3) {
//     zoom.value = Math.min(zoom.value + 0.25, 3)
//   }
// }

// const zoomOut = () => {
//   if (zoom.value > 0.5) {
//     zoom.value = Math.max(zoom.value - 0.25, 0.5)
//   }
// }

// const resetZoom = () => {
//   zoom.value = 1
// }

// 下载当前编辑结果（带背景颜色）
const downloadCurrent = () => {
  const canvas = editCanvas.value
  
  // 如果选择了非透明背景，需要合并背景色
  if (bgColor.value !== 'transparent') {
    const tempCanvas = document.createElement('canvas')
    tempCanvas.width = canvas.width
    tempCanvas.height = canvas.height
    const tempCtx = tempCanvas.getContext('2d')
    
    // 先填充背景色
    tempCtx.fillStyle = bgColor.value
    tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height)
    
    // 再绘制原图像
    tempCtx.drawImage(canvas, 0, 0)
    
    // 导出带背景的图片
    tempCanvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `manual-matting-${Date.now()}.png`
      a.click()
      URL.revokeObjectURL(url)
      toastSuccess('下载成功')
    }, 'image/png')
  } else {
    // 透明背景直接下载
    canvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `manual-matting-${Date.now()}.png`
      a.click()
      URL.revokeObjectURL(url)
      toastSuccess('下载成功')
    }, 'image/png')
  }
}

// 显示确认对话框的辅助函数
const showConfirm = (title, message) => {
  return new Promise((resolve, reject) => {
    confirmDialogTitle.value = title
    confirmDialogMessage.value = message
    confirmDialogCallback.value = resolve
    confirmDialogCancelCallback.value = reject
    showConfirmDialog.value = true
  })
}

// 处理对话框确认
const handleDialogConfirm = () => {
  if (confirmDialogCallback.value) {
    confirmDialogCallback.value(true)
    confirmDialogCallback.value = null
    confirmDialogCancelCallback.value = null
  }
}

// 处理对话框取消
const handleDialogCancel = () => {
  if (confirmDialogCancelCallback.value) {
    confirmDialogCancelCallback.value(false)
    confirmDialogCallback.value = null
    confirmDialogCancelCallback.value = null
  }
}

// 确认编辑（带背景颜色）
const confirmEdit = async () => {
  try {
    const confirmed = await showConfirm('确认保存', '确认使用手动抠图结果替换原来的结果吗？')
    if (!confirmed) return
  } catch {
    return // 用户取消
  }
  
  // 🔑 设置确认状态，禁止使用画笔
  isConfirmed.value = true
  // 设置保存状态，禁用所有控件
  isSaving.value = true
  
  const canvas = editCanvas.value
  
  // 如果选择了非透明背景，需要合并背景色
  if (bgColor.value !== 'transparent') {
    const tempCanvas = document.createElement('canvas')
    tempCanvas.width = canvas.width
    tempCanvas.height = canvas.height
    const tempCtx = tempCanvas.getContext('2d')
    
    // 先填充背景色
    tempCtx.fillStyle = bgColor.value
    tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height)
    
    // 再绘制原图像
    tempCtx.drawImage(canvas, 0, 0)
    
    // 导出带背景的图片（PNG无质量参数，固定无损）
    tempCanvas.toBlob((blob) => {
      emit('confirm', blob)
    }, 'image/png')
  } else {
    // 透明背景直接保存（PNG无质量参数，固定无损）
    canvas.toBlob((blob) => {
      emit('confirm', blob)
    }, 'image/png')
  }
}

// 关闭编辑器
const handleClose = async () => {
  if (history.value.length > 1) {
    try {
      const confirmed = await showConfirm('确认关闭', '您有未保存的修改，确定要关闭吗？')
      if (!confirmed) return
    } catch {
      return // 用户取消
    }
  }
  emit('close')
}

// 监听 visible 变化
let isInitialized = false

watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (!isInitialized) {
      init()
      isInitialized = true
    }
    // 🔑 重置确认状态
    isConfirmed.value = false
  } else {
    // 清理
    history.value = []
    canUndo.value = false
    isConfirmed.value = false
    isSaving.value = false
    isInitialized = false
  }
})

onUnmounted(() => {
  if (rafId != null) {
    cancelAnimationFrame(rafId)
    rafId = null
  }
  pendingPoint.value = null
  cachedRect.value = null
})

// 获取背景样式
const getBackgroundClass = () => {
  return bgColor.value === 'transparent' ? 'checkered-bg' : ''
}

const getBackgroundStyle = () => {
  if (bgColor.value === 'transparent') {
    return {}
  }
  return {
    backgroundColor: bgColor.value
  }
}

// 处理颜色变化
const handleColorChange = () => {
  // 颜色改变时强制更新视图
  console.log('Background color changed to:', bgColor.value)
}

// 监听缩放 - 移除这个，因为我们不需要CSS transform缩放
// watch(zoom, (newVal) => {
//   if (editCanvas.value) {
//     editCanvas.value.style.transform = `scale(${newVal})`
//   }
//   if (originalCanvas.value) {
//     originalCanvas.value.style.transform = `scale(${newVal})`
//   }
// })

// 移除挂载时的重复初始化，统一由visible侦听器控制

// 已由上方侦听器处理初始化与关闭场景，避免重复调用导致历史入栈两次
</script>

<style scoped>
.manual-matting-editor {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
}

.editor-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  overflow: auto;
}

.editor-container {
  background: white;
  border-radius: 16px;
  width: 100%;
  max-width: 1400px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}

/* 顶部工具栏 */
.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 16px 16px 0 0;
}

.back-btn {
  background: white;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 0.9rem;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.back-btn:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.back-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(50%);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 8px 20px;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(50%);
}

.undo-btn {
  background: #6b7280;
  color: white;
}

.undo-btn:hover:not(:disabled) {
  background: #4b5563;
}

.undo-btn:disabled {
  background: #d1d5db;
  cursor: not-allowed;
  opacity: 0.6;
}

.confirm-btn {
  background: #10b981;
  color: white;
}

.confirm-btn:hover {
  background: #059669;
}

.download-btn {
  background: #3b82f6;
  color: white;
}

.download-btn:hover {
  background: #2563eb;
}

/* 主编辑区 */
.editor-main {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

/* 左侧画布区 */
.canvas-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
  overflow: auto;
  background: #f5f5f5;
}

.canvas-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.canvas-wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  flex: 1;
}

.canvas-box {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.canvas-title {
  font-size: 1rem;
  font-weight: 600;
  color: #374151;
  margin: 0;
  text-align: center;
}

.canvas-content {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: visible;
  border: 2px solid #e5e7eb;
  position: relative;
  min-height: 500px;
}

.checkered-bg {
  background-image: 
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%),
    linear-gradient(-45deg, #e5e7eb 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, #e5e7eb 75%),
    linear-gradient(-45deg, transparent 75%, #e5e7eb 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.white-bg {
  background-color: white;
}

.black-bg {
  background-color: black;
}

.canvas {
  display: block;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
}

.edit-canvas {
  cursor: crosshair;
}

.edit-canvas.canvas-disabled {
  cursor: not-allowed;
  opacity: 0.7;
  pointer-events: none;
}

/* 缩放控制 */
.zoom-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.zoom-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 6px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  color: #374151;
}

.zoom-btn:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.zoom-value {
  font-size: 0.95rem;
  font-weight: 600;
  color: #374151;
  min-width: 50px;
  text-align: center;
}

/* 右侧工具面板 */
.tools-panel {
  width: 320px;
  background: white;
  border-left: 1px solid #e5e7eb;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.panel-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.tool-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tool-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.9rem;
  font-weight: 600;
  color: #4b5563;
}

.tool-value {
  color: #667eea;
  font-weight: 700;
}

.tool-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.tool-btn {
  padding: 12px;
  border: 2px solid #e5e7eb;
  background: white;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  color: #374151;
}

.tool-btn:hover {
  border-color: #667eea;
  background: #f9fafb;
}

.tool-btn.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea08 0%, #764ba208 100%);
  color: #667eea;
}

.tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(50%);
}

.tool-slider {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #e5e7eb;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.tool-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #667eea;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.4);
}

.tool-slider::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #667eea;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.4);
}

.tool-slider:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.tool-slider:disabled::-webkit-slider-thumb {
  cursor: not-allowed;
  background: #9ca3af;
}

.tool-slider:disabled::-moz-range-thumb {
  cursor: not-allowed;
  background: #9ca3af;
}

.slider-marks {
  display: flex;
  justify-content: space-between;
  font-size: 0.75rem;
  color: #9ca3af;
}

.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
}

.color-picker-input {
  width: 60px;
  height: 40px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  background: white;
}

.color-picker-input::-webkit-color-swatch-wrapper {
  padding: 0;
}

.color-picker-input::-webkit-color-swatch {
  border: none;
  border-radius: 4px;
}

.color-picker-input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(50%);
}

.color-text-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  color: #374151;
  background: #f9fafb;
}

.color-text-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
}

.color-text-input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #e5e7eb;
}

.transparent-btn {
  padding: 6px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 0.85rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  margin-left: auto;
}

.transparent-btn:hover {
  border-color: #667eea;
  background: #f9fafb;
}

.transparent-btn.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea08 0%, #764ba208 100%);
  color: #667eea;
  font-weight: 600;
}

.transparent-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(50%);
}

/* 删除了重置按钮样式 */

.tool-hint {
  padding: 16px;
  background: #eff6ff;
  border-left: 3px solid #3b82f6;
  border-radius: 8px;
  font-size: 0.85rem;
  line-height: 1.6;
  color: #374151;
}

.tool-hint p {
  margin: 8px 0;
}

.tool-hint strong {
  color: #1f2937;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .editor-main {
    flex-direction: column;
  }

  .tools-panel {
    width: 100%;
    border-left: none;
    border-top: 1px solid #e5e7eb;
    max-height: 300px;
  }

  .canvas-wrapper {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: stretch;
  }

  .action-btn {
    flex: 1;
  }

  .canvas-section {
    padding: 16px;
  }

  .tools-panel {
    padding: 16px;
  }
}
</style>

